#!/usr/bin/python3
# coding=utf-8
"""
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: YangYunYi
# Create: 2020-11-04
"""

import os
import json
import subprocess
import zipfile
import autoimport.logmodule.logger as logger
import autoimport.getdependinfo.utils as utils

this_logger = logger.init('getrequires')
logger.add_file_handler(this_logger, "getrequires", "getrequires")

DOWNLOAD_PATH = "download"


def build_query_command(pkg_name):
    self_depend_request_payload = {"db_list": ["mainline", "bringInRely", "fedora30"],
                                   "selfbuild": "1",
                                   "withsubpack": "1",
                                   "packtype": "source",
                                   'packagename': pkg_name}
    request_payload_str = json.dumps(self_depend_request_payload)
    header_str = 'content-type: application/json'
    url = "https://pkgmanagedebug.openeuler.org/api/dependInfo/download/selfDepend"
    file_name = "{}_query.zip".format(pkg_name)
    file_path = utils.get_file_path(DOWNLOAD_PATH, file_name)
    command = "curl -H '{0}' -X POST -d '{1}' -o {2} {3}".format(header_str,
                                                                 request_payload_str,
                                                                 file_path, url)
    return command


def send_curl_command(pkg_list):
    for pkg_name in pkg_list:
        curl_command = build_query_command(pkg_name)
        try:
            result = subprocess.check_call(
                curl_command, stderr=subprocess.STDOUT, shell=True)
            if result == 0:
                this_logger.info(
                    "Get %s pkgship selfbuild succeed.", pkg_name)
            else:
                this_logger.error(
                    "Get %s pkgship selfbuild failed.", pkg_name)
        except subprocess.TimeoutExpired as time_err:
            this_logger.error(
                "Command is time out.package:%s, error: %s", pkg_name, time_err)
        except subprocess.CalledProcessError as call_err:
            this_logger.error(
                "Command:is failed.package:%s, error: %s", pkg_name,
                call_err.output.decode(encoding="utf-8"))


def unzip_file(zip_file_path, output_path):
    zip_file = zipfile.ZipFile(zip_file_path, 'r')
    file_list = zip_file.namelist()
    for file in file_list:
        zip_file.extract(file, output_path)


def unzip_all_depend_file(pkg_list):
    zip_list = ["{}_query.zip".format(pkg) for pkg in pkg_list]
    zip_path_list = [utils.get_file_path(DOWNLOAD_PATH, file_name) for file_name in zip_list]
    output_path = utils.get_file_path(DOWNLOAD_PATH, "")
    for zip_path in zip_path_list:
        if not os.path.isfile(zip_path):
            this_logger.error(
                "Not found the zip file:%s.", zip_list)
            continue
        unzip_file(zip_path, output_path)


def get_selfdepend_csv(pkg_list):
    # 使用curl命令查询自编译依赖
    # send_curl_command(pkg_list)
    # 解压文件
    unzip_all_depend_file(pkg_list)
